local gamelib = require "club.threecard.gamelib"
local slotlib = require "club.threecard.slotlib"
local components = slotlib.require "components"

local slot_system = slotlib.systems.slot_system
local class = gamelib.entitas.class
local Matcher = gamelib.entitas.Matcher
local GroupEvent = gamelib.entitas.GroupEvent

local parse_resultinfo_system = class("parse_resultinfo_system", slot_system)

function parse_resultinfo_system:initialize()
    self.context.machine:replace(components.result_info_component, nil);
end

function parse_resultinfo_system:get_trigger()
    return {{Matcher({components.result_info_component}), GroupEvent.ADDED}};
end

function parse_resultinfo_system:filter(entity)
    return entity:has(components.result_info_component)
end

function parse_resultinfo_system:execute(entitas)
    if entitas:size() ~= 1 then
        gamelib.log.error("数据错误，结果组件不可能>1")
        return;
    end

    entitas:foreach(function(e)
        local info = e:get(components.result_info_component).info;

        local payout = info.payout;
        local offsets = info.reel_offsets;
        local multiplied = info.multiplied;
        local free_times = info.free_times;
        local frames = info.frames;

        --todo 这个下注数量 应该 开始转的时候传进来
        multiplied = math.floor(payout/self.ingame.app.store.machine.getters.bet_value);
        -- 客户端从1 开始
        for i = 1, #offsets do
            offsets[i] = offsets[i] + 1;
        end

        if e:has(components.payout_component) then
            e:get(components.payout_component).payout = payout;
        end

        if e:has(components.reel_offset_component) then
            e:get(components.reel_offset_component).reel_offsets = offsets;
        end

        if e:has(components.blaze_win_component) then
            e:get(components.blaze_win_component).multiplied = multiplied;
        end

        if e:has(components.frames_component) then
            e:get(components.frames_component).frames = frames;
        end

        if e:has(components.freespin_component) then
            local freespin_component = e:get(components.freespin_component);
            if not freespin_component.total_value then
                freespin_component.total_value = 0;
            end
            freespin_component.left_times = freespin_component.left_times + free_times;    
            if free_times > 0 then
                freespin_component.is_trigger = true;
            end

            if freespin_component.in_free then
                freespin_component.total_value = freespin_component.total_value + payout;
                freespin_component.left_times = freespin_component.left_times - 1;
            end
        end
    end)
end

function parse_resultinfo_system:cleanup()
    self.context.machine:get(components.result_info_component).info = nil;
end

return parse_resultinfo_system